package org.yysd.example;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class HttpClientGUI extends JFrame {

    private JPanel contentPane;
    private JTextField urlTextField;
    private JComboBox<String> methodComboBox;
    private JTextArea headersTextArea;
    private JTextArea paramsTextArea;
    private JTextArea responseTextArea;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HttpClientGUI frame = new HttpClientGUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public HttpClientGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 800, 600);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));

        JPanel topPanel = new JPanel();
        contentPane.add(topPanel, BorderLayout.NORTH);
        topPanel.setLayout(new BorderLayout(0, 0));

        JLabel urlLabel = new JLabel("URL:");
        topPanel.add(urlLabel, BorderLayout.WEST);

        urlTextField = new JTextField();
        topPanel.add(urlTextField, BorderLayout.CENTER);
        urlTextField.setColumns(10);

        JButton sendButton = new JButton("Send");
        sendButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sendHttpRequest();
            }
        });
        topPanel.add(sendButton, BorderLayout.EAST);

        JPanel centerPanel = new JPanel();
        contentPane.add(centerPanel, BorderLayout.CENTER);
        centerPanel.setLayout(new GridLayout(2, 1, 0, 0));

        JPanel requestPanel = new JPanel();
        centerPanel.add(requestPanel);
        requestPanel.setLayout(new BorderLayout(0, 0));

        JPanel requestHeaderPanel = new JPanel();
        requestPanel.add(requestHeaderPanel, BorderLayout.NORTH);
        requestHeaderPanel.setLayout(new BorderLayout(0, 0));

        JLabel lblNewLabel_1 = new JLabel("Request Headers:");
        requestHeaderPanel.add(lblNewLabel_1, BorderLayout.NORTH);

        headersTextArea = new JTextArea();
        requestHeaderPanel.add(new JScrollPane(headersTextArea), BorderLayout.CENTER);

        JPanel requestParamsPanel = new JPanel();
        requestPanel.add(requestParamsPanel, BorderLayout.CENTER);
        requestParamsPanel.setLayout(new BorderLayout(0, 0));

        JLabel lblNewLabel_2 = new JLabel("Request Params:");
        requestParamsPanel.add(lblNewLabel_2, BorderLayout.NORTH);

        paramsTextArea = new JTextArea();
        requestParamsPanel.add(new JScrollPane(paramsTextArea), BorderLayout.CENTER);

        JPanel responsePanel = new JPanel();
        centerPanel.add(responsePanel);
        responsePanel.setLayout(new BorderLayout(0, 0));

        JLabel lblNewLabel_3 = new JLabel("Response:");
        responsePanel.add(lblNewLabel_3, BorderLayout.NORTH);

        responseTextArea = new JTextArea();
        responsePanel.add(new JScrollPane(responseTextArea), BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel();
        contentPane.add(bottomPanel, BorderLayout.SOUTH);
        bottomPanel.setLayout(new BorderLayout(0, 0));

        JLabel lblNewLabel = new JLabel("Method:");
        bottomPanel.add(lblNewLabel, BorderLayout.WEST);

        String[] methods = {"GET", "POST", "PUT", "DELETE"};
        methodComboBox = new JComboBox<>(methods);
        bottomPanel.add(methodComboBox, BorderLayout.CENTER);

        // Set default method as GET
        methodComboBox.setSelectedIndex(0);

        // Set up the layout
        pack();
        setLocationRelativeTo(null);

    }

    private void sendHttpRequest() {
        String url = urlTextField.getText();
        String method = (String) methodComboBox.getSelectedItem();
        String headersText = headersTextArea.getText();
        String paramsText = paramsTextArea.getText();

        Map<String, String> headers = parseKeyValuePairs(headersText);
        Map<String, String> params = parseKeyValuePairs(paramsText);

        StringBuilder response = new StringBuilder();

        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod(method);

            // Set request headers
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // Set request parameters for POST and PUT requests
            if ("POST".equals(method) || "PUT".equals(method)) {
                connection.setDoOutput(true);
                String paramsString = getParamsString(params);
                connection.getOutputStream().write(paramsString.getBytes());
            }

            // Get response
            int responseCode = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // Display response
            responseTextArea.setText("Response Code: " + responseCode + "\n" + response.toString());
        } catch (IOException e) {
            e.printStackTrace();
            responseTextArea.setText("Error occurred: " + e.getMessage());
        }
    }

    private Map<String, String> parseKeyValuePairs(String input) {
        Map<String, String> map = new HashMap<>();
        String[] lines = input.split("\\n");
        for (String line : lines) {
            String[] parts = line.split(":");
            if (parts.length == 2) {
                String key = parts[0].trim();
                String value = parts[1].trim();
                map.put(key, value);
            }
        }
        return map;
    }

    private String getParamsString(Map<String, String> params) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (stringBuilder.length() > 0) {
                stringBuilder.append("&");
            }
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return stringBuilder.toString();
    }
}
